import {
  CanActivate,
  ExecutionContext,
  Injectable,
  Inject,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { AppService } from './app.service';
import { Reflector } from '@nestjs/core';

@Injectable()
export class LoginGuard implements CanActivate {
  @Inject(AppService)
  private readonly appService: AppService;

  @Inject('person')
  private readonly person: {
    name: string;
    age: number;
  };

  @Inject(Reflector)
  private readonly reflector: Reflector;

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const classMetadata = this.reflector.get<string[]>(
      'roles',
      context.getClass(),
    );
    const methodMetadata = this.reflector.get<string[]>(
      'roles',
      context.getHandler(),
    );

    // interceptor 中同样可以通过 reflector 取出 class 或者 handler 上的 metdadata

    // 通过 reflector 的 api 拿到它的 metadata 判断有没有设置权限，没有就放行，有就进行下一步判断
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      return true;
    }
    return true;

    // 判断用户是否有权限
    const { user } = context.switchToHttp().getRequest();
    return roles.some((role) => user && user.roles?.includes(role));

    console.log('LoginGuardLoginGuardLoginGuard');
    console.log('classMetadata===', classMetadata);
    console.log('methodMetadata===', methodMetadata);
    console.log('LoginGuard roles===', roles);

    return true;
  }
}
